package org.weso.lodin.dao;

import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

import junit.framework.Assert;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.weso.lodin.exceptions.DocumentBuilderException;
import org.weso.lodin.exceptions.LodinModelException;
import org.weso.lodin.generated.CountryEnum;
import org.weso.lodin.generated.Datawb;
import org.weso.lodin.generated.Datawb.Data;
import org.weso.lodin.generated.Datawb.Data.Indicator;
import org.weso.lodin.to.ObservationTO;
import org.weso.lodin.utils.DataWBXMLBind;
import org.weso.lodin.utils.DocumentBuilderHelper;
import org.weso.lodin.utils.StatusUtils;

public class WorldBankDataDAOImpl implements WorldBankDataDAO {
	protected static Logger logger = Logger.getLogger(WorldBankDataDAOImpl.class);

	public List<ObservationTO> getObservations(List<String> sources) {
		List<ObservationTO> observations = new LinkedList<ObservationTO>();
		try {
			for(String source:sources){
				logger.info("Loading source "+source);
				ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
				InputStream in = classLoader.getResourceAsStream(source);
				Document doc;
				doc = DocumentBuilderHelper.getDocumentFromInputStream(in);
				Datawb value = DataWBXMLBind.getInstance().restoreIndicator(doc);
				for(Data data : value.getData()){
					observations.add(createObservationFrom(data));
				}
			}			
			return observations;
		} catch (DocumentBuilderException e) {
			throw new LodinModelException(e, "Loading observations");
		}
	
		
	}
	private ObservationTO createObservationFrom(Data data) {
		Indicator indicator = data.getIndicator().get(0);
		String title = indicator.getId()+"#"+indicator.getContent();
		String dataType = "float";
		String country  = data.getCountry().getId();
		CountryEnum countryType = CountryEnum.ISO_CODE_2;
		String countryAlt = data.getCountry().getContent();
		CountryEnum countryTypeAlt = CountryEnum.NAME;
		String value = ""+data.getValue();
		String year = ""+data.getDate();
		String measureId = "";
		ObservationTO obs =  new ObservationTO(title, dataType, country, countryType, countryAlt, countryTypeAlt, value, year, measureId);
		obs.setStatus(StatusUtils.NORMAL);
		return obs;
	}

}

